//创建用户小仓库
import { defineStore } from 'pinia'
import { getToken, setToken, removeToken } from '@/utils/token'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import type { UserState } from './types/type'
import { constantRoute } from "../../router/routes"

let useUserStore = defineStore('user', {
    // 小仓库存储数据地方
    state: (): UserState => {
        return {
            token: getToken(),
            menuRoutes: constantRoute,
            username: '',
        }

    },
    // 异步 | 逻辑的地方
    actions: {
        // 用户登录的方法
        async userLogin(data: any) {
            // 登录请求
            let result: LoginResponseData = await reqLogin(data);
            if (result.code == 200) {
                // 登录成功
                // pinia | vuex 存储的数据其实利用js对象存储的 不是持久化的
                this.token = (result.data as string);
                // 持久化存储token
                setToken(result.data as string);
                return 'ok';
            } else {
                // 登录失败
                return "fail"
            }
        },
        // 获取用户信息 进行存储仓库[头像、名字]
        async getUserInfo() {
            let reuslt: any = await reqUserInfo();
            if (reuslt.code == 200) {
                this.username = reuslt.data.username;
            }

        },
        // 退出登录
        async userLogout() {
            // 发送退出登录请求
            let result: any = await reqLogout();
            if (result.code == 200) {
                this.token = '';
                this.username = '';
                removeToken();
            }
        }
    },
    getters: {

    }

})

export default useUserStore

